package com.gxuwz.zhangjiahui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zhangjiahui.entity.*;
import com.gxuwz.zhangjiahui.service.*;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@Controller
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    private IProjectService iProjectService;
    @Autowired
    private IInstructorService iInstructorService;
    @Autowired
    private IStudentService iStudentService;
    @Autowired
    private ITeamService iTeamService;
    @Autowired
    private IFundsService iFundsService;
    @Autowired
    private IBudgetService iBudgetService;
    @Autowired
    private IEnclosureService iEnclosureService;



    /**
     * 查询全部信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @Pointcut
    @ResponseBody
    @RequestMapping(value = "/findProject")
    public ModelAndView findProject(ModelAndView modelAndView, Page page, Integer pageNumber, Project project,
                                    @Param("projectId") String projectId,
                                    @Param("keyState") Integer keyState,
                                    HttpServletRequest request, HttpServletResponse response) {
        if(request.getSession().getAttribute("nowResult") != null){
            if (!request.getSession().getAttribute("nowResult").equals("now")) {
                request.getSession().setAttribute("result", "");
            }
            request.getSession().setAttribute("nowResult", "");
        }
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("project_id");
        // 进行模糊查询!!!
        if(projectId != null && projectId != ""){
            wrapper.like("project_id", projectId);
            request.getSession().setAttribute("projectId", projectId);
        }else {
            request.getSession().setAttribute("projectId", "");
        }
        // 判断是否查询获奖项目
        if(keyState != null && keyState == 1){
            wrapper.eq("key_state", 1);
        }
        // 判断是否是学生，如果是只能看到自己带领的项目
        if(request.getSession().getAttribute("teamStuNo") != null){
            if(Integer.valueOf(String.valueOf(request.getSession().getAttribute("teamStuNo"))) == 1){ // 如果存在团队项目，且自己为队长
                // and ( a or b )： 语法: wrapper.and(i -> i.eq().or().eq())
                wrapper.and(i -> i.eq("stu_no", request.getSession().getAttribute("studentNo")).or()
                        .eq("team_id", request.getSession().getAttribute("teamNo")));
            }else { // 如果存在单人项目
                wrapper.eq("stu_no", request.getSession().getAttribute("studentNo"));
            }
        }
        // 判断是否是指导老师查看信息，如果是只能看到自己指导的学生信息，进行审批
        if(request.getSession().getAttribute("instructorNow") != null){
            wrapper.like("instructor_id", request.getSession().getAttribute("instructorNow"));
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Project> projectIPage = iProjectService.selectProjectPage(page, wrapper);
        // 存放page，内有当前页数
        modelAndView.addObject("page", page);
        System.out.println("总条数"+projectIPage.getTotal());
        System.out.println("总页数"+projectIPage.getPages());
        // 存放总页数
        modelAndView.addObject("pages", (int)projectIPage.getPages());
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)projectIPage.getPages()];
        for(int i=0; i< (int)projectIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        modelAndView.addObject("pagesList", pagesList);
        modelAndView.addObject("numberPages", projectIPage.getTotal());
        List<Project> projectList = projectIPage.getRecords();
        System.out.println("projectList = "+projectList);
        modelAndView.addObject("projectList", projectList);

        // 查询学生信息
        List<Student> studentList = iStudentService.findStudentAll();
        modelAndView.addObject("studentList", studentList);

        // 查询指导老师信息
        List<Instructor> instructorList = iInstructorService.findInstructorAll();
        modelAndView.addObject("instructorList", instructorList);

        // 查询团队信息
        List<Team> teamList = iTeamService.findTeamAll();
        modelAndView.addObject("teamList", teamList);

        // 查询团队信息
        List<Funds> fundsList = iFundsService.findFundsAll();
        modelAndView.addObject("fundsList", fundsList);

        // 根据年度查询预算方案
        Budget budget = new Budget();
        // 存放当前年份
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
        budget.setBudgetYear(formatter.format(new Date()));
        List<Budget> budgetList = iBudgetService.findBudgetByYear(budget);
        modelAndView.addObject("budgetList", budgetList);

        // 判断是否查询获奖项目
        if(keyState != null && keyState == 1){
            modelAndView.setViewName("project/project_list_state");
        }else {
            modelAndView.setViewName("project/project_list");
        }

        return modelAndView;
    }



    /**
     * 添加/修改 信息
     * @param project
     * @return
     */
    @RequestMapping(value = "/addEditProject")
    public ModelAndView addEditProject(Project project, Funds funds, HttpServletRequest request,
                                       @Param("projectState") Integer projectState,
                                       @Param("keyNow") Integer keyNow,
                                       @Param("approvalState") String approvalState,
                                       @Param("approvalStateText") String approvalStateText,
                                       @RequestParam("file") MultipartFile file,
                                       ModelAndView modelAndView) throws IOException {
        if(projectState != null){
            project.setProjectState(projectState);
        }
        Project project1 = iProjectService.findProjectById(project);
        System.out.println("project = " + project);
        System.out.println("project1 = " + project1);

        // 新增信息
        if(project1 == null){
            if(funds != null){
                // 添加经费预算
                iFundsService.addFunds(funds);
            }
            // 给予标识
            project.setStateNow(1);
            System.out.println("进入新增");
            try {
                iProjectService.addProject(project);
                request.getSession().setAttribute("result", "addTrue");
                request.getSession().setAttribute("nowResult", "now");
            }catch (Exception e){
                request.getSession().setAttribute("result", "addFalse");
                request.getSession().setAttribute("nowResult", "now");
            }

            if(file != null){ // 附件上传，新增附件内容
                // 上传附件内容
                if(file.isEmpty()){
                    System.out.println("上传失败！,请选择文件夹");
                }
                String fileName = file.getOriginalFilename();
                String pathNow = "\\src\\main\\resources\\static\\file\\";
                String filePath = System.getProperty("user.dir") + pathNow;
                File dest = new File(filePath + fileName);
                file.transferTo(dest);

                // 新增附件信息
                Enclosure enclosure = new Enclosure();
                // 新增
                String timestamp = String.valueOf(new Date().getTime());
                String mun = (int) (Math.random()*900 + 100) + "";
                System.out.println("FJ" + timestamp + mun);
                enclosure.setEnclosureId("FJ" + timestamp + mun);

                enclosure.setProjectId(project.getProjectId());
                enclosure.setEnclosureName(fileName);
                enclosure.setEnclosureUrl("/file/");

                iEnclosureService.addEnclosure(enclosure);

            }
        }
        // 修改信息
        if(project1 != null){
            // 修改内容
            System.out.println("进入修改");
            // 如果keyNow为8，9则存在拒绝批准，8：学院部门拒批；9：指导老师拒批
            if(keyNow != null){
                System.out.println("keyNow = " + keyNow);
                if(keyNow == 8){
                    project1.setApprovalStateOne(1);
                    project1.setEvaluateStateOne("批准");
                }else if(keyNow == 9){
                    project1.setApprovalStateTwo(1);
                    project1.setEvaluateStateTwo("批准");
                }
                project1.setStateNow(1);
                try {
                    iProjectService.updateProjectById(project1);
                    request.getSession().setAttribute("result", "editTrue");
                    request.getSession().setAttribute("nowResult", "now");
                }catch (Exception e){
                    request.getSession().setAttribute("result", "editFalse");
                    request.getSession().setAttribute("nowResult", "now");
                }
            }else if(approvalState != null){ // 如果approvalState为8，9则存在拒绝批准，8：学院部门拒批；9：指导老师拒批
                System.out.println("approvalState = " + approvalState);
                // 如果原来审批为空，现审批存在内容，则进行修改
                if(approvalState.equals("8")){
                    project1.setApprovalStateOne(2);
                    project1.setEvaluateStateOne(approvalStateText);
                }else if(approvalState.equals("9")){
                    project1.setApprovalStateTwo(2);
                    project1.setEvaluateStateTwo(approvalStateText);
                }
                project1.setStateNow(2);
                try {
                    iProjectService.updateProjectById(project1);
                    request.getSession().setAttribute("result", "editTrue");
                    request.getSession().setAttribute("nowResult", "now");
                }catch (Exception e){
                    request.getSession().setAttribute("result", "editFalse");
                    request.getSession().setAttribute("nowResult", "now");
                }
            }else {
                try {
                    iProjectService.updateProjectById(project);
                    request.getSession().setAttribute("result", "editTrue");
                    request.getSession().setAttribute("nowResult", "now");
                }catch (Exception e){
                    request.getSession().setAttribute("result", "editFalse");
                    request.getSession().setAttribute("nowResult", "now");
                }
            }
        }
        modelAndView.setViewName("redirect:/project/findProject");
        return modelAndView;
    }



    /**
     * 删除信息
     * @param projectId
     * @return
     */
    @GetMapping(value = "/deleteProject")
    public ModelAndView deleteProject(HttpServletRequest request, ModelAndView modelAndView,
                             @Param("projectId") String projectId) {
        Project project = new Project();
        project.setProjectId(projectId);
        try {
            iProjectService.deleteProjectById(project);
            request.getSession().setAttribute("result", "deleteTrue");
            request.getSession().setAttribute("nowResult", "now");
        }catch (Exception e){

        }
        modelAndView.setViewName("redirect:/project/findProject");
        return modelAndView;
    }

}
